package com.farm.wcp.job;

import com.farm.core.auth.domain.LoginUser;
import com.farm.core.sql.query.DataQuery;
import com.farm.wcp.util.SpringUtils;
import com.wts.exam.domain.Paper;
import com.wts.exam.domain.RoomPaper;
import com.wts.exam.service.PaperServiceInter;
import com.wts.exam.service.RoomPaperServiceInter;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.List;

/**
 * 定时删除临时试卷
 */
@Component
public class DeleteTempPaperJob implements Job {
    /**
     * 获得当前用户
     *
     * @return
     */
    private LoginUser getUser() {
        return new LoginUser() {
            @Override
            public String getName() {
                return "quartz";
            }

            @Override
            public String getLoginname() {
                return "quartz";
            }

            @Override
            public String getId() {
                return "quartz";
            }

            @Override
            public String getType() {
                return "NONE";
            }

            @Override
            public String getIp() {
                return "NONE";
            }
        };
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 查找 答题室状态为归档 pstate==4 的答题室
        // 查找 考试试卷 roomPaper 的答卷
        // 查找 EXAMTYPEID 为 0 的答卷（临时试卷）
        // 删除试卷
        DataQuery query = DataQuery.getInstance("1",
                "rp.ID AS ID, rp.PAPERID AS PAPERID, rp.ROOMID AS ROOMID",
                "wts_room_paper rp LEFT JOIN wts_paper p ON p.ID = rp.PAPERID LEFT JOIN wts_room r ON r.ID = rp.ROOMID ");
        query.addSqlRule(" AND ISNULL( p.EXAMTYPEID ) AND r.PSTATE = '4'");
        query.setNoCount();
        query.setPagesize(1000);
        try {
            List<RoomPaper>  list= query.search().getObjectList(RoomPaper.class);
            for (int i = 0; i < list.size(); i++) {
                RoomPaper roomPaper = list.get(i);
                Paper paper = SpringUtils.getBean(PaperServiceInter.class).getPaperEntity(roomPaper.getPaperid());
                if (paper != null) {
                    SpringUtils.getBean(PaperServiceInter.class).deletePaperEntity(roomPaper.getPaperid(), getUser());
                }
                RoomPaper roompaperEntity = SpringUtils.getBean(RoomPaperServiceInter.class).getRoompaperEntity(roomPaper.getId());
                if (roompaperEntity != null) {
                    SpringUtils.getBean(RoomPaperServiceInter.class).deleteRoompaperEntity(roomPaper.getId(), getUser());
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
